﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace PhotoFileMigrator
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private static string defaultPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

        private static string CSVFileName = string.Empty;

        private static StreamReader runReader = null;

        private static string failFileName = string.Empty;

        private static string notFoundFileName = string.Empty;
        private void Main_Load(object sender, EventArgs e)
        {

        }

        private void btn_Look_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folder = new FolderBrowserDialog())
            {
                folder.Description = "请选择你要加载的文件夹！";
                folder.SelectedPath = defaultPath;
                if (!string.IsNullOrEmpty(txt_Path.Text.Trim()))
                {
                    folder.SelectedPath = txt_Path.Text;
                }
                if (folder.ShowDialog() == DialogResult.OK)
                {
                    txt_Path.Text = folder.SelectedPath;
                }
            }
        }

        private void btn_Import_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Multiselect = true;
                openFile.InitialDirectory = defaultPath;
                openFile.Title = "请选择文件";
                openFile.Filter = "*.csv|*.csv|所有文件 (*.*)|*.*";
                string fileName = string.Empty;
                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    txt_CSV.Text = openFile.FileName;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btn_Run_Click(object sender, EventArgs e)
        {

            RetModel retModel = new RetModel();

            int count = 0, successCount = 0, failCount = 0;
            string searchPath = txt_Path.Text.Trim().ToString();
            try
            {
                if (!System.IO.Directory.Exists(searchPath))
                {
                    MessageBox.Show("检索目录不存在，请重新选择检索目录！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (Common.CheckFile(txt_CSV.Text.Trim()))
                {
                    CSVFileName = Path.GetFileNameWithoutExtension(txt_CSV.Text.Trim().ToString());
                    StreamReader sr = new StreamReader(txt_CSV.Text.Trim());
                    runReader = sr;
                }

                if (runReader == null)
                {
                    MessageBox.Show("CSV文件不存在，请导入！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool isCut = rbt_Cut.Checked ? true : false;

                string head = runReader.ReadLine();
                string line = string.Empty;

                while ((line = runReader.ReadLine()) != string.Empty)
                {
                    var list = Common.ToList(line);
                    if (list.Count < 3)
                    {
                        if (list.Count > 0)
                        {
                            Loggers.BaseLogger.Info(string.Format("错误的数据行：Field：{0}", list[0].ToString()));
                        }
                        
                        if (runReader.EndOfStream)
                        {
                            break;
                        }
                        continue;
                    }

                    var sourceFileName = System.IO.Path.Combine(searchPath, list[1].ToString());
                    var destFileName = System.IO.Path.Combine(searchPath, list[2].ToString());

                    retModel = Common.MoveOrCopyFile(sourceFileName, destFileName, isCut);

                    if (retModel.RetrunState == ReturnType.Success)
                    {
                        successCount++;
                        continue;
                    }
                    else if (retModel.RetrunState == ReturnType.Fail || retModel.RetrunState == ReturnType.FileExists)
                    {
                        if (string.IsNullOrEmpty(failFileName))
                        {
                            var saveName = string.Format("{0}-Fail", CSVFileName);
                            failFileName = string.Format(@"{0}\FailFile\{1}.csv", defaultPath, saveName);
                            Common.SaveDataToCSV(head, notFoundFileName);
                        }
                        Common.SaveDataToCSV(line, failFileName);
                        failCount++;
                        Loggers.BaseLogger.Debug(retModel.ReturmMsg);
                        continue;
                    }
                    else if (retModel.RetrunState == ReturnType.FileNotFound)
                    {
                        if (string.IsNullOrEmpty(notFoundFileName))
                        {
                            var saveName = string.Format("{0}-NotFound", CSVFileName);
                            notFoundFileName =string.Format(@"{0}\NotFound\{1}.csv",defaultPath,saveName);
                            var headList = Common.ToList(head);
                            Common.SaveDataToCSV(headList[0].ToString(), notFoundFileName);
                        }
                        Common.SaveDataToCSV(list[0].ToString(), notFoundFileName);
                        failCount++;
                        Loggers.BaseLogger.Debug(retModel.ReturmMsg);
                        continue;
                    }
                    count++;
                }

                MessageBox.Show("文件迁移完成！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                runReader.Dispose();
            }
            catch (Exception ex)
            {
                Loggers.FormLogger.Fatal(ex.ToString());
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
